package org.morningangel.servlet.android;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.morningangel.bean.User;
import org.morningangel.dao.UserDao;
import org.morningangel.dao.impl.UserDaoImpl;
import org.morningangel.util.SendSecurityCodeUtil;

@WebServlet(name= "AndroidGetSecurityCodeServlet", urlPatterns = "/android/getSecurityCode")
public class GetSecurityCodeServlet extends HttpServlet {
	private static final long serialVersionUID = -1652835224037906933L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Integer isBind = Integer.parseInt(request.getParameter("isBind"));
		String phone = request.getParameter("telNum");
		UserDao userDao = new UserDaoImpl();
		Integer status = 0;
		String identifyCode = "0";
		User u = userDao.login(phone);
		if(isBind==2){//找回密码
			if (u != null) {
				identifyCode = SendSecurityCodeUtil.send(u.getPhone());
				status = 1;
			}
		}else  {//绑定手机号
			//注册或绑定手机
			if (u == null) {
				//手机号可用
				identifyCode = SendSecurityCodeUtil.send(phone);		
				status = 1;
			}
		} 
		
		PrintWriter out = response.getWriter();
		out.print("{\"isSuccess\":\"" + status + "\", \"identifyCode\":\"" +  identifyCode + "\"}");
		out.flush();
		out.close();
	}

}
